package com.example.tool.ui;

import com.example.tool.module.ModuleInputEnum;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;

import javax.swing.JComponent;
import javax.swing.text.JTextComponent;
import java.util.function.Function;

public class HToolViewItem<T extends JComponent> {
  // 标题
  private final ModuleInputEnum title;
  // 组件
  private final T t;
  // 是否选中
  private final boolean isFocus;
  // 获取组件的值
  private final Function<T, String> fun;

  public HToolViewItem(ModuleInputEnum title, T t) {
    this(title, t, false);
  }

  public HToolViewItem(ModuleInputEnum title, T t, boolean isFocus) {
    this(title, t, isFocus, t1 -> {
      if (t1 instanceof TextFieldWithBrowseButton) {
        return ((TextFieldWithBrowseButton) t1).getText();
      } else if (t1 instanceof JTextComponent) {
        t1.setToolTipText(title.getValue());
        return ((JTextComponent) t1).getText();
      } else if (t1 instanceof ComboBox) {
        t1.setToolTipText(title.getValue());
        return (String) ((ComboBox<?>) t1).getSelectedItem();
      }
      return null;
    });
  }

  public HToolViewItem(ModuleInputEnum title, T t, Function<T, String> fun) {
    this(title, t, false, fun);
  }

  public HToolViewItem(ModuleInputEnum title, T t, boolean isFocus, Function<T, String> fun) {
    this.title = title;
    this.t = t;
    this.isFocus = isFocus;
    this.fun = fun;
  }

  public ModuleInputEnum getTitle() {
    return title;
  }


  public T getT() {
    if (t instanceof JTextComponent) {
      t.setToolTipText(title.getValue());
    }
    return t;
  }

  public boolean isFocus() {
    return isFocus;
  }

  public String getValue() {
    return fun.apply(t);
  }
}
